package com.guoxin.mashibing;

import java.util.LinkedList;

public class SynchronizationContainer<T> {

    private static final int MAX = 10;
    private int count = 0;
    private final LinkedList<T> container = new LinkedList<>();

    public synchronized void put(T t) {
        while (container.size() >= MAX) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        container.add(t);
        count++;
        this.notifyAll();
    }

    public synchronized T get() {
        T t = null;
        while (container.size() == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        t = container.removeFirst();
        count--;
        this.notifyAll();
        return t;
    }

    public static void main(String[] args) throws InterruptedException {
        SynchronizationContainer<String> sc = new SynchronizationContainer<>();

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 5; j++) {
                    System.out.println(sc.get());
                }
            }, "C" + i).start();
        }

        Thread.sleep(2000);

        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                for (int j = 0; j < 25; j++) {
                    sc.put(Thread.currentThread().getName() + "--" + j);
                }
            }, "P" + i).start();
        }
    }
}
